/******************************************************************************
 * @File name   :      IWSUserAccountServiceImpl.java
 *
 * @Author      :      Panxing Wu
 *
 * @Date        :      2011-7-1
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * 2011-7-1 上午11:23:21        Panxing Wu     1.0            Initial Version
 * 2011-9-30 上午10:06:09 HeHao       1.1             Change Method employeeDtoToDomain
 * 2011-10-19 下午02:47:22 wangzhize       1.2        employeeinfo int to Integer ,fix type mismatch error
 *****************************************************************************/
package com.cap.bts.framework.dm.employeemgnt.service.impl;

import java.text.SimpleDateFormat;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cap.bts.commonfunc.ge.dealer.service.IDealerService;
import com.cap.bts.framework.approvalrule.constants.ApplicationTypeConstants;
import com.cap.bts.framework.approvalrule.constants.ApprovalCategoryConstants;
import com.cap.bts.framework.approvalrule.constants.ApprovalStatus;
import com.cap.bts.framework.approvalrule.service.IApprovalRuleService;
import com.cap.bts.framework.approvalrule.util.ApprovalRuleUtil;
import com.cap.bts.framework.codemapping.service.ICodeMapping;
import com.cap.bts.framework.common.constant.BrandConstants;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.dm.approval.dao.IDealerUsrGrpApprovalDao;
import com.cap.bts.framework.dm.approval.domain.UserGroupApplication;
import com.cap.bts.framework.dm.employeemgnt.constants.EmployeeUserAccountConstants;
import com.cap.bts.framework.dm.employeemgnt.service.IUserAccountService;
import com.cap.bts.framework.usermgnt.constant.EmployeeStatus;
import com.cap.bts.framework.usermgnt.constant.UserGroupCode;
import com.cap.bts.framework.usermgnt.constant.UserGroupLevel;
import com.cap.bts.framework.usermgnt.dao.IEmployeeInfoDao;
import com.cap.bts.framework.usermgnt.dao.IOrganizationDao;
import com.cap.bts.framework.usermgnt.dao.IUserGroupDao;
import com.cap.bts.framework.usermgnt.domain.EmployeeInfo;
import com.cap.bts.framework.usermgnt.domain.Organization;
import com.cap.bts.framework.usermgnt.domain.User;
import com.cap.bts.framework.usermgnt.domain.UserGroup;
import com.cap.bts.framework.usermgnt.service.IUserMgntService;

/**
 *
 */
@Transactional(rollbackFor = AppException.class)
@Service
public class UserAccountServiceImpl implements IUserAccountService {

	private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

	@Autowired
	private IUserMgntService userMgntService;

	@Resource(name = "employeeInfoDao")
	private IEmployeeInfoDao employeeInfoDao;

	@Resource(name = "dealerUsrGrpApprovalDao")
	private IDealerUsrGrpApprovalDao userGroupApplicationDao;

	@Resource(name = "userGroupDao")
	private IUserGroupDao userGroupDao;
	@Resource(name = "organizationDao")
	private IOrganizationDao organizationDao;

	@Autowired
	private IDealerService dealerService;

	@Autowired
	private ICodeMapping codeMappingService;

	@Resource(name = "approvalRuleServiceImpl")
	private IApprovalRuleService approvalRuleService;
	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

//	/**
//	 * {@inheritDoc} overridden:
//	 * 
//	 * @Date : 2011-7-1
//	 * @see com.cap.bts.gdms.dm.employeemgnt.service.IUserAccountService#handleUserGroupApplication(com.cap.bts.gdms.dm.employeemgnt.dto.WSDealerEmployeeDto)
//	 **/
//	@Override
//	public boolean handleUserGroupApplication(WSDealerEmployeeDto dto)
//			throws AppException {
//
//		boolean result = true;
//		User operator = userMgntService.getUserByUserCode(dto
//				.getLastUpdateByCode()); // 查找操作人
//		EmployeeInfo employeeInfo = null;
//		// 设置类型
//		if (dto.getOperateType() == EmployeeUserAccountConstants.OPERATE_TYPE_EMPLOYEE) {
//			if (dto.getUserCode() != null) {
//				employeeInfo = employeeInfoDao.getEmployeeInfoByUserCode(dto.getUserCode());
//			}
//			if (employeeInfo == null) {
//				employeeInfo = new EmployeeInfo();
//			}
//			employeeInfo.setEmploymentStatusId(new Long(
//					EmployeeStatus.PEND_TO_CREATE));
//			employeeInfo.setCreateBy(operator.getId());
//			try {
//				// 数据转换
//				employeeDtoToDomain(dto, employeeInfo, operator);
//			} catch (ParseException e) {
//				result = false;
//				e.printStackTrace();
//			}
//			employeeInfoDao.save(employeeInfo);
//			Organization org = organizationDao.getOrganizationByOrgCode(dto
//					.getOrgCode());
//			saveUser(dto, operator, employeeInfo, org);
//			User user = userMgntService.getUserByUserCode(dto.getUserCode());
//			UserGroup userGroup = userGroupDao.getUserGroupByCode(dto.getUserGroupCode());
//			employeeInfo.setUserId(user.getId());
//			employeeInfoDao.update(employeeInfo);
//			this.saveUserGroupApplication(userGroup, org, dto.getBrandId(),
//					employeeInfo, operator,null);
//
//		} else if (dto.getOperateType() == EmployeeUserAccountConstants.OPERATE_TYPE_USERGROUP) {
//
//			employeeInfo = employeeInfoDao.getEmployeeInfoByUserCode(dto
//					.getUserCode());
//			employeeInfo.setEmploymentStatusId(new Long(
//					EmployeeStatus.PEND_TO_CHANGE));
//			try {
//				employeeDtoToDomain(dto, employeeInfo, operator);
//			} catch (ParseException e) {
//				result = false;
//				e.printStackTrace();
//
//			}
//			employeeInfoDao.update(employeeInfo);
//			Organization org = organizationDao.getOrganizationByOrgCode(dto
//					.getOrgCode());
//			
//			// this.updateUserDefaultUserGroup(user, userGroup, operator);
//			User user = userMgntService.getUserByUserCode(dto.getUserCode());
//			UserGroup userGroup = userGroupDao.getUserGroupByCode(dto.getUserGroupCode());
//			this.saveUserGroupApplication(userGroup, org, dto.getBrandId(),
//					employeeInfo, operator,user);
//		}
//
//		return result;
//	}

	private void saveUserGroupApplication(UserGroup userGroup,
			Organization org, long brandId, EmployeeInfo employeeInfo,
			User operator,User user) throws AppException {
		// 用户组
		if (userGroup != null && org != null) {
			int appCategory = getUsrGrpApprovalCategory(
					userGroup.getUserGroupCode(),
					userGroup.getUserGroupLevel(), employeeInfo.getBrandId());
			UserGroupApplication userGroupApplication = new UserGroupApplication(
					(int) brandId, appCategory);
			userGroupApplication.setEmployeeInfo(employeeInfo);
			if (employeeInfo.getEmploymentStatusId() == EmployeeStatus.PEND_TO_CREATE) {

				userGroupApplication
						.setOperationType(EmployeeUserAccountConstants.USER_GROUP_APPLICATION_OPERATIONTYPE_ADD);// 设置结点类型
			} else if (employeeInfo.getEmploymentStatusId() == EmployeeStatus.PEND_TO_CHANGE) {
				userGroupApplication
						.setOperationType(EmployeeUserAccountConstants.USER_GROUP_APPLICATION_OPERATIONTYPE_UPDATE);// 设置结点类型
			}

			Organization applicationOrg = organizationDao
					.getOrganizationByOrgCode(org.getOwnerId());
			userGroupApplication.setOrgCode(org.getOrgCode());
			userGroupApplication.setDealerOrgId(applicationOrg.getId());
			userGroupApplication.setResult(ApprovalStatus.NOT_APPROVAL);
			userGroupApplication.setUsrgrpCode(userGroup.getUserGroupCode());
			userGroupApplication.setCreateBy(operator.getId());
			userGroupApplication.setLastUpdateBy(operator.getId());
			if(user!=null && user.getUserGroup()!=null){
				userGroupApplication.setSrcGrpCode(user.getUserGroup().getUserGroupCode());
			}
			userGroupApplicationDao.save(userGroupApplication);
			String startStepCode = ApprovalRuleUtil.getRuleStartPoint(
					(int) brandId, appCategory);
			approvalRuleService.createStartRuleSteps(userGroupApplication,
					userGroupApplication.getId(),
					ApplicationTypeConstants.USERGROUP_APPLICATION_TYPE,
					startStepCode);
		}
	}

//	private void employeeDtoToDomain(WSDealerEmployeeDto dto,
//			EmployeeInfo employeeInfo, User operator) throws AppException,
//			ParseException {
//
//		employeeInfo.setEmployeeName(dto.getUserName());
//		employeeInfo.setEmployeeCode(dto.getEmployeeCode());
//		employeeInfo.setUserCode(dto.getUserCode());
//		employeeInfo.setBrandId(dto.getBrandId());
//		employeeInfo.setIsSgm(EmployeeIsSgmConstants.IS_SGM_NO);
//		DealerInfo dealerInfo = dealerService.getDealerByDealerCode(dto
//				.getDealerCode());
//		if (dealerInfo != null) {
//			employeeInfo.setDealerId(dealerInfo.getId());
//		}
//		employeeInfo.setExportData(dto.getExportData());
//
//		CodeInfo certificateCodeInfo = codeMappingService.getCodeInfoByCode(dto
//				.getCertificateTypeCode());
//		employeeInfo.setCertificateType(certificateCodeInfo.getId());
//		employeeInfo.setCertificateNo(dto.getCertificateCode());
//		employeeInfo.setBirthPlace(dto.getBirthPlace());
//		CodeInfo educationCodeInfo = codeMappingService.getCodeInfoByCode(dto
//				.getEducationCode());
//		employeeInfo.setEducationId(educationCodeInfo.getId());
//
//		CodeInfo genderCodeInfo = codeMappingService.getCodeInfoByCode(dto
//				.getGenderCode());
//		employeeInfo.setGenderId(genderCodeInfo.getId());
//		CodeInfo marriageICodeInfo = codeMappingService.getCodeInfoByCode(dto
//				.getMarriageCode());
//		employeeInfo.setMarriageId(marriageICodeInfo.getId());
//		if (Utils.notEmpty(dto.getBirthDateStr())) {
//			employeeInfo.setBirthDate(dateFormat.parse(dto.getBirthDateStr()));
//		}
//		if (Utils.notEmpty(dto.getMobilePhone())) {
//			employeeInfo.setMobilePhone(Long.parseLong(dto.getMobilePhone()));
//		}
//		employeeInfo.setEmail(dto.getEmail());
//		employeeInfo.setAddress(dto.getAddress());
//		employeeInfo.setOnboardDate(dateFormat.parse(dto.getOnboardDateStr()));
//		if (Utils.notEmpty(dto.getDriverLicenseDateStr())) {
//			employeeInfo.setDriverLicenseDate(dateFormat.parse(dto
//					.getDriverLicenseDateStr()));
//		}
//		if (Utils.notEmpty(dto.getPassTrainingDateStr())) {
//			employeeInfo.setPassTrainingDate(dateFormat.parse(dto
//					.getPassTrainingDateStr()));
//		}
//
//		employeeInfo.setHasDriverLicense(dto.getHasDriverLicense());
//		if (Utils.notEmpty(dto.getBrandFirstServiceDateStr())) {
//			employeeInfo.setBrandFirstServiceDate(dateFormat.parse(dto
//					.getBrandFirstServiceDateStr()));
//		}
//		employeeInfo.setIsBrandTraining(dto.getIsBrandTraining());
//		employeeInfo.setRegister(operator.getId());
//		employeeInfo.setRegisterDate(new Date());
//		employeeInfo.setPhotoUrl(dto.getPhotoUrl());
//		employeeInfo.setIsDeboardCompleted(CommonConstants.NO); // 设置
//																// DeboardComplete
//																// 状态
//		if (operator != null) {
//			employeeInfo.setLastUpdateBy(operator.getId());
//		}
//	}

//	private void saveUser(WSDealerEmployeeDto dto, User operator,
//			EmployeeInfo employeeInfo, Organization org) throws AppException {
//
//		UserDto userDto = new UserDto();
//		// userDto.setDefaultUserGroupCode(dto.getUserGroupCode());
//		userDto.setBrandId(dto.getBrandId());
//		userDto.setUserType(UserType.DEALER);// 设置用户类型
//		userDto.setEmployeeInfoId(employeeInfo.getId());
//		userDto.setUserCode(employeeInfo.getUserCode());
//		userDto.setEmployeeName(employeeInfo.getEmployeeName());
//		// 设置用户组织结构
//		if (dto.getOrgCode() != null) {
//			Organization applicationOrg = organizationDao
//					.getOrganizationByOrgCode(org.getOwnerId());
//			userDto.setEmployerOrgId(applicationOrg.getId());
//		}
//		userDto.setPassword(EmployeeUserAccountConstants.INIT_PASSWORD);
//		userDto.setOperatorId(operator.getId());
//		userDto.setDefaultUserGroupCode(dto.getUserGroupCode());
//		userMgntService.createUserByDto(userDto);
//	}

	/*
	 * private void updateUserDefaultUserGroup(User user, UserGroup userGroup,
	 * User operator) {
	 * 
	 * user.setUserGroup(userGroup); user.setLastUpdateBy(operator.getId());
	 * userDao.update(user); }
	 */
	private static int getUsrGrpApprovalCategory(String userGroupCode,
			int level, Long brandId) {

		// 销售经理、市场经理 BUI 没有自己的审批流程是关键岗位
		// 有自己审批岗位就用自己，没有就用1：普通岗位。2：关键岗位
		if (UserGroupCode.GMCODE.getValue().equals(userGroupCode)) {// 总经理有自己审批流程
			return ApprovalCategoryConstants.GENERAL_MANAGER;
		} else if (UserGroupCode.MARKETMANAGER.getValue().equals(userGroupCode)) {// 市场经理
			if (brandId.toString().equals(BrandConstants.BRAND1 + "")) {// 市场经理BUI没有自己的审批流程是关键岗位
				return ApprovalCategoryConstants.KEY_STATION;// 关键岗位
			}
			return ApprovalCategoryConstants.MARKET_MANAGER;
		} else if (UserGroupCode.SALEMANAGER.getValue().equals(userGroupCode)) {// 销售经理
			if (brandId.toString().equals(BrandConstants.BRAND1 + "")) {// 销售经理 BUI
																		// 没有自己的审批流程是关键岗位
				return ApprovalCategoryConstants.KEY_STATION;// 关键岗位
			}
			return ApprovalCategoryConstants.SALE_MANAGER;
		} else if (UserGroupLevel.KEY.getValue() == level) {
			return ApprovalCategoryConstants.KEY_STATION;// 关键岗位
		} else {// 非关键岗位
			return ApprovalCategoryConstants.NORMAL_STATION;
		}
		/*
		 * if (UserGroupCode.SALEMANAGER.getValue().equals(userGroupCode)) {
		 * return ApprovalCategoryConstants.SALE_MANAGER; } else if
		 * (UserGroupCode.GMCODE.getValue().equals(userGroupCode)) { return
		 * ApprovalCategoryConstants.GENERAL_MANAGER; } else if
		 * (UserGroupCode.MARTPERSON.getValue().equals(userGroupCode)) { return
		 * ApprovalCategoryConstants.MARKET_MANAGER; } else if
		 * (UserGroupCode.SALECONSULTANT.getValue().equals(userGroupCode)) {
		 * return ApprovalCategoryConstants.KEY_STATION; } else { return
		 * ApprovalCategoryConstants.NORMAL_STATION; }
		 */
	}

	/**
	 * {@inheritDoc} overridden:
	 * 
	 * @Date : Mar 29, 2012
	 * @see com.cap.bts.gdms.dm.employeemgnt.service.IUserAccountService#handleUserEmployeeApplication(com.cap.bts.gdms.dm.employeemgnt.dto.WSDealerEmployeeDto)
	 **/
//	@Override
//	public boolean handleUserEmployeeApplication(WSDealerEmployeeDto dto)
//			throws AppException {
//		boolean result = true;
//		// 查找操作人
//		User operator = userMgntService.getUserByUserCode(dto
//				.getLastUpdateByCode());
//		EmployeeInfo employeeInfo = null;
//		try {
//			employeeInfo = employeeInfoDao.getEmployeeInfoByUserCode(dto
//					.getUserCode());
//			// 数据转换，employeeInfo中填充数据
//			employeeDtoToDomain(dto, employeeInfo, operator);
//			employeeInfoDao.update(employeeInfo);
//		} catch (ParseException e) {
//			result = false;
//			e.printStackTrace();
//		}
//		return result;
//	}

	/**
	 * {@inheritDoc} overridden:
	 * 
	 * @Date : May 23, 2012
	 * @see com.cap.bts.gdms.dm.employeemgnt.service.IUserAccountService#saveFilingEmployee(com.cap.bts.gdms.dm.employeemgnt.dto.WSFilingEmployeeDto)
	 **/
//	@Override
//	public boolean saveFilingEmployee(WSFilingEmployeeDto submitDto)
//			throws AppException {
//		EmployeeFiling employeeFiling;
//		boolean result = true;
//		if (Utils.notNullAndZero(submitDto.getId())) {
//			employeeFiling = employeeFilingDao
//					.findFilingEmployeeByEmployeeCode(submitDto
//							.getEmployeeCode());
//			employeeFiling.setDriverLicenseDate(null);
//			employeeFiling.setPassTrainingDate(null);
//		} else {
//			employeeFiling = new EmployeeFiling();
//		}
//		employeeFiling.setEmployeeCode(submitDto.getEmployeeCode());
//		employeeFiling.setEmployeeName(submitDto.getEmployeeName());
//		employeeFiling.setGenderId(submitDto.getGenderId());
//		employeeFiling.setMobilePhone(submitDto.getMobilePhone());
//		employeeFiling.setEmail(submitDto.getEmail());
//		employeeFiling.setCertificateType(submitDto.getCertificateId());
//		employeeFiling.setCertificateNo(submitDto.getCertificateCode());
//		employeeFiling.setMarriageId(submitDto.getMarriageId());
//		employeeFiling.setBirthPlace(submitDto.getBirthPlace());
//		employeeFiling.setEducationId(submitDto.getEducationId());
//		employeeFiling.setAddress(submitDto.getAddress());
//		employeeFiling.setUserGroupId(submitDto.getUserGroupId());
//		employeeFiling.setIsBrandTraining(submitDto.getIsBrandTraining());
//		employeeFiling.setHasDriverLicense(submitDto.getHasDriverLicense());
//		employeeFiling.setBrandId(submitDto.getBrandId());
//		employeeFiling.setDealerId(submitDto.getDealerId());
//		try {
//			employeeFiling.setBirthDate(df.parse(submitDto.getBirthDateStr()));
//			employeeFiling.setBrandFirstServiceDate(df.parse(submitDto
//					.getBrandFirstServiceDateStr()));
//			employeeFiling.setOnboardDate(df.parse(submitDto
//					.getOnboardDateStr()));
//			if (submitDto.getDriverLicenseDateStr() != null) {
//				employeeFiling.setDriverLicenseDate(df.parse(submitDto
//						.getDriverLicenseDateStr()));
//			}
//			if (submitDto.getPassTrainingDateStr() != null) {
//				employeeFiling.setPassTrainingDate(df.parse(submitDto
//						.getPassTrainingDateStr()));
//			}
//
//			if (Utils.notNullAndZero(submitDto.getId())) {
//				employeeFilingDao.update(employeeFiling);
//			} else {
//				employeeFilingDao.save(employeeFiling);
//			}
//		} catch (ParseException e) {
//
//			e.printStackTrace();
//			result = false;
//			throw new AppException(SysErrorCodes.SYS_DATE_PARSE_ERROR,
//					e.getCause());
//		} catch(Exception e){
//			e.printStackTrace();
//			result = false;
//			throw new AppException(SysErrorCodes.SYSTEM_ERROR,
//					e.getCause());
//		}
//
//		return result;
//	}


}
